package cn.hiapi.shopkeeper.service.shopkeeper;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.shopkeeper.entity.shopkeeper.ActivityPreview;
import cn.hiapi.shopkeeper.jpa.shopkeeper.ActivityPreviewJpa;
import cn.hiapi.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.LongBinaryOperator;
import java.util.stream.Collectors;

/**
 * @author AdinZ
 * @date 2023/2/7 23:05
 */
@Service
public class ActivityPreviewService extends AbsBasicService<ActivityPreviewJpa, ActivityPreview, Long> {

    private final String KEY = "CORE:ACTIVITY:PREVIEW";

    private String getKey(long aid, long uid) {
        return new StringBuffer().append(aid).append("-").append(uid).toString();
    }

    private ActivityPreview getByAid(long aid) {
        List<ActivityPreview> previews = this.findList(new QueryWrapper().eq("aid", aid));

        ActivityPreview preview;
        if (previews.isEmpty()) {
            preview = new ActivityPreview();
            preview.setAid(aid);
        } else {
            preview = previews.get(0);
            if (previews.size() > 1) {
                long total = previews.stream().mapToLong(e -> e.getPreview()).reduce((left, right) -> left + right).getAsLong();
                preview.setPreview(total);
                List<ActivityPreview> collect = previews.stream().filter(e -> e.getAid() != preview.getAid()).collect(Collectors.toList());
                this.delete(collect);
            }
        }
        return preview;
    }


    /**
     * 增加浏览用户
     *
     * @param aid
     */
    public void preview(long uid, long aid) {
        if (this.redisService.get(KEY, this.getKey(aid, uid)) != null) return;
        ActivityPreview preview = this.getByAid(aid);
        preview.setPreview(preview.getPreview() + 1);
        preview.setUpdated(System.currentTimeMillis());
        this.update(preview);
        this.redisService.set(KEY, this.getKey(aid, uid), DateUtils.format());
    }


    public long getPreview(long aid) {
        ActivityPreview preview = this.getByAid(aid);

        return preview != null ? preview.getPreview() : 0;
    }
}
